/*
 * Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
 * Follow up:
 * Can you solve it without using extra space?
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) { }
};

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *fast = head, *slow = head;
        while (fast) {
            fast = fast->next;
            if (!fast) {
                break;
            } else {
                fast = fast->next;
            }
            slow = slow->next;
            if (fast == slow) {
                break;
            }
        }
        /* check */
        if (!fast) {
            return NULL;
        }
        slow = head;
        while (fast && slow) {
            if (fast == slow) {
                return fast;
            }
            fast = fast->next;
            slow = slow->next;
        }
        return NULL;
    }
};

int main() {
    return 0;
}
